from flask import Blueprint, render_template, request, url_for, session, g, flash, redirect
from exts import db
from forms import EditInfoForm
from models import AdminModel

# __name__代表当前模块
admin = Blueprint('admin', __name__, url_prefix='/admin')


@admin.route('/change_info', methods=['GET', 'POST'])
def change_info():
    if request.method == 'GET':
        form = EditInfoForm()
        return render_template('change-info.html', form=form)
    elif request.method == 'POST':
        form = EditInfoForm(request.form)
        if form.validate_on_submit():
            current_account = AdminModel.query.filter_by(admin_name=g.account.admin_name).first()
            current_account.admin_name = form.name.data
            db.session.commit()
            g.account.admin_name = form.name.data
            flash(u'成功修改个人信息！')
            return redirect(url_for('user.user_info'))
        form.name.data = g.account.admin_name
        return render_template('change-info.html', form=form)
